package validator

import (
	"fmt"
	"reflect"
)

type StringBorder struct {
	Value   int
	Include bool
}

type StringRange struct {
	min *StringBorder
	max *StringBorder
}

func NewStringRangeValidator(
	min *StringBorder,
	max *StringBorder) *StringRange {
	return &StringRange{
		min: min,
		max: max,
	}
}
func (r *StringRange) String() string {
	var str string
	if r.min != nil {
		if r.min.Include {
			str = fmt.Sprintf("[%d", r.min.Value)
		} else {
			str = fmt.Sprintf("(%d", r.min.Value)
		}
	} else {
		str = "("
	}
	if r.max != nil {
		if r.max.Include {
			str = fmt.Sprintf("%s:%d]", str, r.max.Value)
		} else {
			str = fmt.Sprintf("%s:%d)", str, r.max.Value)
		}
	} else {
		str = fmt.Sprintf("%s:)", str)
	}
	return str
}

func (r *StringRange) IsValidate(field string, data reflect.Value) error {
	var v = len(data.String())
	if r.min != nil {
		if r.min.Include {
			if v < r.min.Value {
				return fmt.Errorf("field [%s]'s length must great then or equals %v", field, r.min.Value)
			}
		} else {
			if v <= r.min.Value {
				return fmt.Errorf("field [%s]'s length must great then %v", field, r.min.Value)
			}
		}
	}
	if r.max != nil {
		if r.max.Include {
			if v > r.max.Value {
				return fmt.Errorf("field [%s]'s length must less then or equals %v", field, r.max.Value)
			}
		} else {
			if v >= r.max.Value {
				return fmt.Errorf("field [%s]'s length must less then %v", field, r.max.Value)
			}
		}
	}
	return nil
}
